# -*- coding: utf-8 -*-
"""
Created on Thu Mar 10 16:39:29 2022

@author: Ewing
"""

import zipfile 
import os 
import fnmatch 
import configparser
import logging
import logging.handlers
import sys
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QMessageBox, QApplication, QLabel


def run():
    if len(sys.argv) > 1:
        config_file_path = sys.argv[1]
    else:
        config_file_path = "config.ini"
    #config_file_path="C:\\Users\\pengzhongqi\\Desktop\\脚本\\MiniTools\\zengwei\\2\\config.ini"
    config = configparser.ConfigParser()
    config.read(config_file_path, encoding='utf-8')
    path = config.get("zip_path", "path")
    extensions = config.get("zip_path", "extensions")
    save_path = config.get("zip_path", "save_path")
    print("正在读取配置文件....")
    print("扫描路径:"+path)
    print("输出路径:"+save_path)
    print("模糊匹配字符:"+extensions)
    print("正在执行脚本-2.多个压缩包文件中提取某一文件")

    def archive1(path,extensions,save_path):
        rootPath= (path)
        pattern = '*.zip'
        for root, dirs, files in os.walk(rootPath):
            for filename in fnmatch.filter(files,pattern):
                with zipfile.ZipFile(os.path.join(root, filename)) as zf:
                    extractor(zf,extensions,save_path)

    def extractor(zip_file,extensions,save_path):
        [zip_file.extract(file,save_path) for file in zip_file.namelist() if extensions in file]

    archive1(path,extensions,save_path)
    print("Extract_Pic.py : The job has been done successfully")
    return True

class win(QWidget):
    def __init__(self):
        super().__init__()
        self.setFixedWidth(180)
        self.setWindowTitle(" ")

        layout = QVBoxLayout()
        openConfig = QPushButton("打开配置", self)
        # openConfig.setText()
        # openTemplate = QPushButton("打开配置模板", self)
        # openTemplate.setText()
        startButton = QPushButton("运行", self)

        layout.addWidget(QLabel("多个压缩包文件中提取某一"))
        layout.addWidget(QLabel("文件"))
        layout.addWidget(openConfig)
        # layout.addWidget(openTemplate)
        # layout.addStretch()
        layout.addWidget(startButton)

        self.setLayout(layout)
        openConfig.clicked.connect(self.openConfig)
        # openTemplate.clicked.connect(self.openTemplate)
        startButton.clicked.connect(self.start)

    def openConfig(self):
        if len(sys.argv) > 1:
            config_file_path = sys.argv[1]
        else:
            config_file_path = "config.ini"
        print(config_file_path)
        # print(len(sys.argv))
        os.system(config_file_path)
        pass

    def start(self):
        try:
            res = run()
        except Exception as e:
            print(repr(e))
            res = False

        if res:
            QMessageBox.information(self, "", "处理成功！")
        else:
            QMessageBox.critical(self, "", "处理失败，请查看后台日志！")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = win()
    main.show()
    sys.exit(app.exec())